import * as vscode from 'vscode';
import { DocumentParser } from './DocumentParser';
import { DocumentViewer } from '../ui/DocumentViewer';
import { ExtensionService } from './ExtensionService';
import path from 'path';
import fs from 'fs';




export class InstanceManager {

    private static _instances: { [key: string]: Instance } = {};


    public static Exists(document: vscode.TextDocument) {
        const key = document.uri.fsPath;
        return key in InstanceManager._instances;
    }


    public static OpenInstance(document: vscode.TextDocument) {
        const key = document.uri.fsPath;
        if (!(key in InstanceManager._instances)) {
            InstanceManager._instances[key] = new Instance(document);
        }
        return InstanceManager._instances[key];
    }

    public static DisposeInstance(inst: Instance) {
        const key = inst.Document.uri.fsPath;
        if (key in InstanceManager._instances) {
            delete InstanceManager._instances[key];
        }
    }
}

class Instance {

    private _viewer: DocumentViewer;
    private _document: vscode.TextDocument;

    private _parser: DocumentParser;

    public get Viewer() {
        return this._viewer;
    }

    public get Document() {
        return this._document;
    }

    public get Parser() {
        return this._parser;
    }

    constructor(document: vscode.TextDocument) {
        this._document = document;
        this._viewer = new DocumentViewer();
        this._parser = new DocumentParser(document);


        this.bindEvents();

    }

    private bindEvents() {

        //#region 初始化
        this.Viewer.OnReady = async () => {

            while (!this._parser.docReady) {
                await new Promise((resolve) => setTimeout(resolve, 100));
            }

            this._parser.getDefaultData()
                .then(data => {
                    this.Viewer.setTitle(`${this.Document.fileName} - 故事线预览`);
                    this.Viewer.pushData(data);
                });
        };
        //#endregion

        //#region 获取数据
        this.Viewer.OnDataRequest = (option) => {
            this.Parser.getDocument(option.pageIndex, option.pageSize, option.keywords)
                .then(data => {
                    this.Viewer.pushData(data);
                });
        };
        //#endregion

        //#region 跳转到指定事件
        this.Viewer.OnFoucusRequest = (option) => {
            const {lineNumber, docPath} = this._parser.searchEvent(option.time, option.groupId, option.title, option.content);

            if (lineNumber >= 0) {
                const visibleEditors = vscode.window.visibleTextEditors;

                for (var i = 0; i < visibleEditors.length; i++) {
                    const editor = visibleEditors[i];
                    if (editor.document.uri.fsPath === docPath) {

                        return vscode.window.showTextDocument(editor.document, {
                            viewColumn: editor.viewColumn,
                            // preserveFocus: false,
                            selection: new vscode.Range(lineNumber, 0, lineNumber, 0),
                        });
                    }
                }

                const doc = vscode.workspace.openTextDocument(docPath);
                doc.then((doc) => {
                    vscode.window.showTextDocument(doc, {
                        viewColumn: vscode.ViewColumn.One,
                        // preserveFocus: false,
                        selection: new vscode.Range(lineNumber, 0, lineNumber, 0),
                    });
                });
            }
        };
        //#endregion

        //#region 跳转到指定页
        this.Viewer.OnGotoRequest = (keywords) => {

            vscode.window.showInputBox({
                placeHolder: '请输入页码',
                value: "1",
                validateInput: (value) => {
                    if (!value) {
                        return '请输入页码';
                    }
                    if (isNaN(Number(value))) {
                        return '请输入数字';
                    }
                    return null;
                }
            }).then(async (value) => {
                if (value) {
                    const pageIndex = Number(value);

                    this.Parser.getDocument(pageIndex, -1, keywords)
                        .then(result => {
                            this.Viewer.pushData(result);
                        })
                        .catch(err => {
                            vscode.window.showErrorMessage(err);
                        });

                }
            });
        };
        //#endregion

        //#region 显示帮助文档
        this.Viewer.OnHelpRequest = () => {
            vscode.env.openExternal(vscode.Uri.parse('https://gitcode.com/lorraine1314/vs-storylineviewer'));
        };
        //#endregion

        //#region 打开链接
        this.Viewer.OnOpenLinkRequest = (link, docPath) => {
            if (link.startsWith('file://')) {
                const dir = path.dirname(docPath);
                const uri = vscode.Uri.file(path.join(dir, link.replace('file://', '')));
                console.log('open file', uri);

                if (!fs.existsSync(uri.fsPath)) {
                    return vscode.window.showErrorMessage(`文件不存在: ${link}`);
                }

                console.log('open file', uri);
                try {
                    vscode.workspace.openTextDocument(uri)
                        .then(doc => {
                            vscode.window.showTextDocument(doc, {
                                viewColumn: vscode.ViewColumn.One, // 在第一个编辑器组打开
                                preview: false,                    // 固定标签页（避免替换预览页）
                                preserveFocus: true,               // 保持当前焦点（可选）
                            });
                        });

                } catch (error) {
                    vscode.window.showErrorMessage(`打开文件失败: ${error}`);
                }
            } else {
                vscode.env.openExternal(vscode.Uri.parse(link));
            }

        };
        //#endregion

        //#region 显示消息
        this.Viewer.OnShowMessageRequest = (text, level) => {
            console.log('showMsg:', text, level);

            if (text) {
                if (level === 'warn') {
                    vscode.window.showWarningMessage(text);

                } else if (level === 'error') {
                    vscode.window.showErrorMessage(text);
                }
                else {
                    const statusBarItem = vscode.window.createStatusBarItem(
                        vscode.StatusBarAlignment.Right,
                        100 // 优先级
                    );
                    statusBarItem.text = text;
                    statusBarItem.show();

                    // 设置定时器自动消失
                    setTimeout(() => statusBarItem.dispose(), 1500);
                }
            }
        };
        //#endregion


        //#region 销毁
        this.Viewer.OnDispose = () => {
            this.dispose();
        };
        //#endregion

    }

    public Refresh() {
        this.Parser.reload()
            .then(() => {

                this.Parser.getDefaultData()
                    .then(data => {
                        this.Viewer.pushData(data);
                    });
            });
    }


    private dispose() {

        this._parser.dispose();

        InstanceManager.DisposeInstance(this);
    }
}